<script setup>
import Api from '@/api/server/group'
import predictApi from '@/api/server/predict'
import thirdGamesApi from "@/api/thirdGames/games";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
let formData = reactive({
  id:"",
  user_id: "",
  mode:null,
  game_id:null,
  interval:"",
  history_draws:"",
  predicted_draws:"",
  status:null,
  conversations:[]
});

const emits = defineEmits(["refreshTable"]);

// 初始化数据
const ruleFormRef = ref();
const btnLoading = ref(false);
const modalShow = ref(false);
const isEdit = ref(false);

const groupList = ref([])
const gameList = ref([])
const disabled = ref(false)

const initModal = ({ row, type }) => {
  modalShow.value = true;
  if (type) {
    for (let key in formData) {
      formData[key] = row[key];
    }
    isEdit.value = true;
  } else {
    isEdit.value = false;
  }
};

watch(()=>formData.game_id,(newVal)=>{
  if(!!newVal){
    disabled.value = true;
  }else{
    disabled.value = false;
  }
},{
  immediate:true
})

// 清空表单对象
const formDataBackUp = Object.assign({}, formData);

// 重置校验与数据
const resetFormKey = () => {
  ruleFormRef.value?.resetFields();
  Object.assign(formData, formDataBackUp);
};

// 校验规则
const rules = ref({
    user_id: [{ required: true, message: t("label.111"), trigger: "blur" }],
    mode: [{ required: true, message: t("label.112"), trigger: "blur" }],
    game_id: [{ required: true, message: t("label.29"), trigger: "change" }],
    interval: [{ required: true, message: t("label.113"), trigger: ['change',"blur"] }],
    history_draws: [{ 
      required: true, message: t("label.114"), trigger: "blur",
    },{
      validator: (rule, value, callback) => {
        if (value > 100) {
          callback(new Error(t("hint.142")))
        } else {
          callback()
        }
      }
    }],
    predicted_draws: [{ 
      required: true, message: t("label.115"), trigger: "blur" 
    },{
      validator: (rule, value, callback) => {
        if (value > 100) {
          callback(new Error(t("hint.143")))
        } else {
          callback()
        }
      }
    }],
    status: [{ required: true, message: t("label.23"), trigger: "blur" }],
  },)

// 取消按钮事件
const cancelBtn = () => {
  //清空列表
  resetFormKey()
  //关闭弹窗
  modalShow.value = false;
  btnLoading.value = false;
};

/* 保存报溢 */
const handleSave = async () => {
  // 校验表单信息
  let isVerify = false;
  ruleFormRef.value && (await ruleFormRef.value.validate((valid) => (isVerify = valid)));
  if (!isVerify) {
    ElMessage.warning(t('hint.134'));
    return;
  }
  const id = formData.id;
  console.log('formData===>',formData)

  if (id) {
    // 编辑
    editFormData(formData);
  } else {
    // 新增
    addFormData(formData);
  }
};


/**
 * 新增事件
 */
 const addFormData = (object) => {
  btnLoading.value = true;
  predictApi.add(object)
    .then((res) => {
      ElMessage.success(t("hint.operationSuccess"));
      modalShow.value = false;
      emits("refreshTable");
    })
    .finally(() => {
      btnLoading.value = false;
    });
};

/**
 * 编辑事件
 */
const editFormData = (object) => {
  btnLoading.value = true;
  predictApi.put(object)
    .then((res) => {
      ElMessage.success(t("hint.operationSuccess"));
      modalShow.value = false;
      emits("refreshTable");
    })
    .finally(() => {
      btnLoading.value = false;
    });
};

const handleChange = (val) => {
  // 使用 filter 找到所有匹配的项
  const res = gameList.value.filter((item) => item.value == val);

  // 检查 res 是否有匹配项
  if (res.length > 0) {
    // 如果有匹配项，取第一个匹配项的 interval
    formData.interval = res[0].interval;
  } else {
    // 如果没有匹配项，赋值为空字符串
    formData.interval = '';
  }
}


const getGroupList = () => {
  Api.getList({ type: 'group', page: 1, per_page: 200 }).then((res) => {
    groupList.value = res.data
  })
}

const getGameList = async () => {
  try {
    let params = { page: 1, per_page: 1000, category_id: 2 } // 彩票id为2
    const result = await thirdGamesApi.getList(params);
    gameList.value = result.data.filter(item => {
      if (item.meta.length > 0) {
        return item
      }
    }).map((item) => {
      return {
        value: item.id,
        label: item.name,
        interval: item.meta[0].value,
      }
    })
  }
  catch (err) {
    console.log(err);
  }
}

onMounted(() => {
  getGroupList()
  getGameList()
})

defineExpose({ initModal });
</script>

<template>
  <el-dialog v-model="modalShow" width="640" align-center :title="isEdit?t('title.31'):t('title.30')" @close="cancelBtn">
    <el-form ref="ruleFormRef" :rules="rules" @submit.enter.prevent label-width="auto" :model="formData" class="form-container">
      <el-form-item :label="t('label.111')" prop="user_id">
        <el-input class="int" v-model="formData.user_id" :placeholder="t('label.111')" clearable />
      </el-form-item>
      <el-form-item :label="t('label.112')" prop="mode">
        <el-select v-model="formData.mode" :placeholder="t('hint.112')" clearable>
          <el-option :label="t('status.big_or_small')" value="big_or_small" />
          <el-option :label="t('status.odd_or_even')" value="odd_or_even" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('label.33')" prop="game_id">
        <el-select v-model="formData.game_id" @change="handleChange">
          <template v-for="option in gameList" :key="option.value">
            <el-option :label="option.label" :value="option.value" />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item :label="t('label.113')" prop="interval">
        <el-input class="int" :disabled="disabled" v-model="formData.interval" :placeholder="t('label.113')" clearable />
      </el-form-item>
      <el-form-item :label="t('label.114')" prop="history_draws">
        <el-input class="int" v-model="formData.history_draws" :placeholder="t('label.114')" clearable />
      </el-form-item>
      <el-form-item :label="t('label.115')" prop="predicted_draws">
        <el-input class="int" v-model="formData.predicted_draws" :placeholder="t('label.115')" clearable />
      </el-form-item>
      <el-form-item :label="t('label.23')" prop="status">
        <el-select v-model="formData.status" :placeholder="t('hint.133')" clearable>
          <el-option :label="t('groupStatus.active')" value="active" />
          <el-option :label="t('groupStatus.inactive')" value="inactive" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('label.116')" prop="conversations">
        <el-select v-model="formData.conversations" multiple clearable>
          <template v-for="option in groupList" :key="option.id">
            <el-option :label="option.name" :value="option.id" />
          </template>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelBtn">{{ t('btn.8') }}</el-button>
      <el-button type="primary" @click="handleSave" :loading="btnLoading">{{ t('btn.1') }}</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.form-item,
.int {
  width: 100%;
}
.btn {
  margin-right: 14px;
}
</style>
